<?php
namespace app\common\model\assay;
use app\api\controller\Pub;
use app\common\model\user\User;
use app\common\model\power\Rolepower;
use app\common\model\company\Contract;
use app\common\model\orderhawa\HawaList;
use think\Model;

//送样列表
class Assaylist extends Model
{
    protected $table = 'assay_list';
    protected $pk    = 'AssayListId';

    const STATEINT  = 0; //初始化 待回款
    const STATEING  = 1; //待登记
    const STATEEND  = 2; //已登记
    const STATEAPPROVAL = 3;//已审批报价

    /**
     * 状态分类
     * @param string $value [description]
     * @return [type]        [description]
     */
    public static function getStatusText($value = '')
    {
        $status = [-1=>'全部订单',0 => '待接收', 1 => '待登记', 2 => '已登记',3=>'已审批'];
        if ($value !== '') {
            return $status[$value];
        }
        return $status;
    }

    public function companyinfo()
    {
        return $this->hasOne('app\common\model\company\Company', 'CompanyId', 'CompanyId');
    }

    public function subuserinfo()
    {
        return $this->hasOne('app\common\model\User\User', 'UserId', 'SubUserId');
    }

    public function reguserinfo()
    {
        return $this->hasOne('app\common\model\User\User', 'UserId', 'RegUserId');
    }

    public function accuserinfo()
    {
        return $this->hasOne('app\common\model\User\User', 'UserId', 'AccUserId');
    }

    /**
     * 创建化验单
     * 如果关联化验单，关联
     * @param  [type] $data [description]
     * @return [type]       [description]
     */
    public static function user_create($idata)
    {   
        if(empty($idata['CompanyId'])){
            return moerr('缺少企业信息');
        }
        $rebate               = new Assaylist();
        $rebate->State        = Assaylist::STATEINT;
        $rebate->CreateTime   = date('Y-m-d H:i:s', time());
        $rebate->SubUserId    = Pub::userid(); //创建服务费的用户id
        $filed                = ['CompanyId', 'SubTime', 'SubImg','SubNote'];
        foreach ($filed as $key => $value) {
            if (isset($idata[$value])) {
                $rebate->$value = $idata[$value];
            }
        }
        //保存
        $rebate->save();
        $id = $rebate->AssayListId;
        //保存化验具体关联危废的信息
        if(!empty($idata['goodinfo'])){
            $data['goodinfo'] = json_decode($idata['goodinfo'],true);
            if(!empty($data['goodinfo'])&&!empty($data['goodinfo'][0]['GoodId'])){
                Assay::user_create($id,$data['goodinfo']);
            }
        }
        return $id;
    }

    //获取列表
      /**
     * 获取订单列表
     * @param  [type] $data    [主数据]
     * @param  string $type    [查询类型/hawa/buss]
     * @param  [type] $is_page [是否分页显示]
     * @return [type]          [description]
     */
    public static function usergetlist($data, $is_page = true)
    {

        $rdata    = new Assaylist;
        $userid = Pub::userid();

        //如果是管理者 -> 全部显示
        if (!Rolepower::ispower(204016)) {
            $lswhere = '';
            //负责送审的人 - >只显示自己所属的登记数据
            if (Rolepower::ispower(201008)) {
                if(!empty($lswhere)){$lswhere = $lswhere .'or';}
                $lswhere = '(SubUserId = '.$userid.')';
            }
            //负责接受的人
            if (Rolepower::ispower(208001)) {
                if(!empty($lswhere)){$lswhere = $lswhere .'or';}
                //已经登记的
                $lswhere = '((AccUserId = '.$userid.')or'.'(RegUserId = '.$userid.'))';
                //还没有登记的 信息
                $lswhere = 'or ( RegUserId is null)';
            }
            if(!empty($lswhere)){
                $rdata = $rdata->where($lswhere);
            }else{
                return moerr('没有权限');
            }
        }
        //删除标记的数据
        if(empty($data['deletestate'])){
            $rdata = $rdata->where('IsDelete',0);
        }else if($data['deletestate']==1){
            $rdata = $rdata->where('IsDelete',1);
        }
        
        $rdata = $rdata->with(['companyinfo','subuserinfo','reguserinfo','accuserinfo'])->visible(['AssayListId','State','CreateTime','SubTime','AccTime','RegTime','AssayTime','companyinfo'=>['Name'],'subuserinfo'=>['Name'],'reguserinfo'=>['Name'],'accuserinfo'=>['Name']]);

        $data['order'] = 'CreateTime desc';
        $option = come_model_option($data, $rdata, $is_page);

        $rdata = $option['rdata'];
        $data  = $option['data'];
        $rdata = $rdata->select();

        $ndata['list'] = $rdata->toArray();

        $ndata['statetext'] = Assaylist::getStatusText();
        if ($is_page) {
            $ndata['pageinfo'] = ['pageindex' => $data['pageindex'], 'pagemax' => $data['count']];
        }
        return $ndata;
    }


    /**
     * 判断服务费状态是否可操作
     * @param  [type] $list [id数组]
     * @return [type]       [返回错误代码]
     */
    public static function liststate($id,$hidden=[],$hidloag=true,$jump = true,$type_state=true){
        $data = Assaylist::where('AssayListId',$id)->find();
        if(empty($data)){
            if($jump){
                return moerr('没有找到您需要的样品信息');
            }else{
                return [];
            }
        }else{
            if($hidloag==true && Rolepower::ispower(204016)){
                $hidloag = false;
            }
            if($hidloag){
                $hidden= array_merge(['OperationLog'],$hidden);
                $data = $data->hidden($hidden)->toArray();
            }elseif(empty($hidden)){
                $data = $data->toArray();
            }else{
                $data = $data->hidden($hidden)->toArray();    
            }
            return sok($data);
        }
    }

    /**
     * 获取创建关联信息/修改关联信息时候需要填写的数据
     * @param  [type] $id   [description]
     * @param  [type] $type [description]
     * @return [type]       [description]
     */
    public function get_view_info($id){
        $data = self::liststate($id,[],true,false);
        if(empty($data)){
            return [];
        }else{
            $rdata = $data['msg'];
            $rdata['StateText'] = Assaylist::getStatusText($rdata['State']);
            return $rdata;
        }
    }

    /**
     * 获取订单信息
     * @param  [type] $id [description]
     * @return [type]     [description]
     */
    public static function getinfo($id,$usertype = 'buss'){
        if($usertype=='mana'){
            $data = self::liststate($id,[],false,true,false);
        }else{
            $data = self::liststate($id,[],true,true,false);
        }
        if (!$data['code']) { return $data; }
        $rdata = $data['msg'];
        $rdata['list'] = Assay::getlist($id,$usertype);
        if(!empty($rdata['SubUserId'])){
            $rdata['subuserinfo'] = User::getpublicinfo($rdata['SubUserId']);
        }
        if(!empty($rdata['AccUserId'])){
            $rdata['accuserinfo'] = User::getpublicinfo($rdata['AccUserId']);
        }
        if(!empty($rdata['RegUserId'])){
            $rdata['reguserinfo'] = User::getpublicinfo($rdata['RegUserId']);
        }
        $rdata['StateText'] = Assaylist::getStatusText($rdata['State']);
        return sok($rdata);
    }


    /**
     * 用户修改信息
     * @param  [type]  $data   [description]
     * @param  boolean $wtnote [是否记录]
     * @param  boolean $nochangemsg [没有变动的话是否提示]
     * @return [type]          [description]
     */
    public static function user_reinfo($data, $wtnote = true,$nochangemsg = true)
    {
        if (empty($data['id'])) {
            return moerr('缺少重要参数');
        }
        $info     = Assaylist::get($data['id']);
        if(empty($info)){
            return moerr('没有找到此条记录');
        }
        $userinfo = User::getinfo();
        $reinfo   = empty($info->OperationLog) ? '' : $info->OperationLog . "\n";
        $reinfo   = $reinfo . '【' . $userinfo->Name . '|' . $userinfo->UserId . '】在' . date('Y-m-d H:i', time()) . '进行了信息调整：';
        $nreinfo  = '';
        // dump($data);
        foreach ($data as $key => $value) {
            $sb = $info->getfiledname($key);
            if (empty($sb)) {
                continue;
            }
            //取原数据
            $ovalue = $info->$key;

            if ($key == 'State' && $value !== $ovalue) {
                $info->$key = $value;
                //value将改变成文字所以提前赋值
                $value   = $info->getStatusText((int) $value);
                $ovalue  = $info->getStatusText((int) $ovalue);
                $nreinfo = $nreinfo . '字段【' . $info->getfiledname($key) . '】由【' . $ovalue . '】修改为【' . $value . '】;' . "\n";
            }  else if ((strpos($key, "Time") !== false) ) {    
                //过滤掉时间相同的数据  
                if(strtotime($ovalue) !== strtotime($value)){
                    $nreinfo    = $nreinfo . '字段【' . $info->getfiledname($key) . '】由【' . $ovalue . '】修改为【' . $value . '】;' . "\n";
                    $info->$key = $value;
                }
            } else if (isset($value) && $ovalue !== $value) {                
                $nreinfo    = $nreinfo . '字段【' . $info->getfiledname($key) . '】由【' . $ovalue . '】修改为【' . $value . '】;' . "\n";
                $info->$key = $value;
            }
        }
        if (!empty($nreinfo)) {
            if ($wtnote) {
                $reinfo             = $reinfo . "\n" . $nreinfo;
                $info->OperationLog = $reinfo;
            }
            $info->save();
        } else {
            if($nochangemsg){
                return moerr('没有找到需要调整的数据');
            }
        }
    }

    /**
     * 获取字段的名字，同时仅可删除带名字的字段
     * @param  [type] $str [description]
     * @return [type]      [description]
     */
    public static function getfiledname($str)
    {
        $filename = [
            'SubTime'  => '送审时间', 'SubUserId'      => '送审人', 'SubImg'=>'送审图片','SubNote'=>'送审备注',
            'AccTime'  => '接收时间', 'AccUserId'      => '接收人', 'AccImg'=>'接收图片','AccNote'=>'接收备注',
            'RegTime'  => '登记时间', 'RegUserId'      => '登记人', 'RegImg'=>'登记图片','RegNote'=>'登记备注',
            'State' => '状态', 'IsDelete' => '是否删除' , 'AssayTime' => '化验时间'
        ];
        if (empty($filename[$str])) {
            return false;
        }
        return $filename[$str];
    }

}
